/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.mp.common.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Json;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.config.WxConfig;
import com.yami.shop.mp.common.model.WeixinMaterial;
import com.yami.shop.mp.common.platform.service.WeixinMaterialService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpNewsArticle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lgh on 2019/05/14.
 */
@RestController
@RequestMapping("/weixin/material")
@Api(tags = "平台端微信material接口")
public class WeixinMaterialController {

    @Autowired
    private WeixinMaterialService weixinMaterialService;
    @Autowired
    private WxConfig wxConfig;

    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('weixin:material:page')")
    @ApiOperation(value = "分页查找微信素材信息")
    public ServerResponseEntity<IPage<WeixinMaterial>> page(PageParam<WeixinMaterial> page,WeixinMaterial weixinMaterial){
        IPage<WeixinMaterial> list = weixinMaterialService.page(page, new LambdaQueryWrapper<WeixinMaterial>()
                .eq(StrUtil.isNotBlank(weixinMaterial.getMediaType()), WeixinMaterial::getMediaType, weixinMaterial.getMediaType())
                .like(StrUtil.isNotBlank(weixinMaterial.getMediaName()), WeixinMaterial::getMediaName, weixinMaterial.getMediaName()));
        return ServerResponseEntity.success(list);
    }

    @PostMapping("/sync/{type}")
    @ApiOperation(value = "根据素材类型同步素材")
    @ApiImplicitParam(name = "type", value = "素材类型 图文，视频，语音，图片", required = true, dataType = "String")
    @PreAuthorize("@pms.hasPermission('weixin:material:sync')")
    public ServerResponseEntity<Void> sync(@PathVariable String type) throws WxErrorException{
        if (StrUtil.isBlank(type)) {
            // 请选择素材类型
            throw new YamiShopBindException("yami.select.source");
        }
        List<WeixinMaterial> allMaterial = new ArrayList<>();
        // 每页大小
        int pageSize = 20;
        // 一共有多少页
        int pageCount = 1;
        // 一共有多少条记录
        int totalCount = 0;
        for (int i = 0; i < pageCount; i++) {
            // 图文素材
            if (WxConsts.MaterialType.NEWS.equals(type)) {
                WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = wxConfig.getWxMpService().getMaterialService().materialNewsBatchGet(i * pageSize, pageSize);
                totalCount = wxMpMaterialNewsBatchGetResult.getTotalCount();
                List<WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem> items = wxMpMaterialNewsBatchGetResult.getItems();
                for (WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem newsItem : items) {
                    WeixinMaterial weixinMaterial = new WeixinMaterial();
                    weixinMaterial.setCreateTime(newsItem.getUpdateTime());
                    weixinMaterial.setMediaId(newsItem.getMediaId());
                    WxMpMaterialNews content = newsItem.getContent();
                    List<WxMpNewsArticle> articles = content.getArticles();

                    // 多余的文章没有实际作用，微信返回的消息只能返回一条
                    WxMpNewsArticle wxMpMaterialNewsArticle = articles.get(0);
                    // 内容保存起来没有实际用处，清除内容
                    wxMpMaterialNewsArticle.setContent(null);
                    weixinMaterial.setContent(Json.toJsonString(wxMpMaterialNewsArticle));
                    weixinMaterial.setMediaName(wxMpMaterialNewsArticle.getTitle());
                    weixinMaterial.setCreateTime(content.getCreateTime());
                    weixinMaterial.setUpdateTime(content.getUpdateTime());
                    weixinMaterial.setMediaType(type);
                    allMaterial.add(weixinMaterial);
                }
            }
            // 其他素材：视频，语音，图片
            else {
                WxMpMaterialFileBatchGetResult wxMpMaterialFileBatchGetResult = wxConfig.getWxMpService().getMaterialService().materialFileBatchGet(type,i*pageSize, pageSize);
                totalCount = wxMpMaterialFileBatchGetResult.getTotalCount();
                List<WxMaterialFileBatchGetNewsItem> items = wxMpMaterialFileBatchGetResult.getItems();
                for (WxMaterialFileBatchGetNewsItem materialItem : items) {
                    WeixinMaterial weixinMaterial = new WeixinMaterial();
                    weixinMaterial.setCreateTime(materialItem.getUpdateTime());
                    weixinMaterial.setMediaId(materialItem.getMediaId());
                    weixinMaterial.setMediaName(materialItem.getName());
                    weixinMaterial.setUpdateTime(materialItem.getUpdateTime());
                    weixinMaterial.setMediaType(type);
                    weixinMaterial.setContent(materialItem.getUrl());
                    allMaterial.add(weixinMaterial);
                }
            }
            // 初始化
            if (i == 0) {
                pageCount = totalCount / pageSize;
                if (totalCount % pageSize > 0) {
                    pageCount +=1 ;
                }
            }
        }
        weixinMaterialService.insertBatch(allMaterial,type);
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/{mediaId}")
    @PreAuthorize("@pms.hasPermission('weixin:material:delete')")
    @ApiOperation(value = "根据素材id删除素材")
    @ApiImplicitParam(name = "mediaId", value = "素材id", required = true, dataType = "String")
    public ServerResponseEntity<Void> delete(@PathVariable String mediaId){
        weixinMaterialService.delete(mediaId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/list")
    @PreAuthorize("@pms.hasPermission('weixin:material:info')")
    @ApiOperation(value = "获取素材列表")
    public ServerResponseEntity<List<WeixinMaterial>> list(){
        return ServerResponseEntity.success(weixinMaterialService.list());
    }
}
